package com.crayfish.banner.widget.calendar2;

import java.util.Calendar;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

/**
 * Created by lin on 2016/8/23.
 */
public class WeekDayView extends View{

    private static final int NUM_COLUMNS = 7;//7列
    private static int ROW_HEIGHT = 50;
    private Paint mDayPaint;//字体画笔
    private Paint mDayBGPaint;//字体背景画笔
    private Paint mDayTagPaint;//标记圆点画笔
    private int mDayColor = Color.parseColor("#000000");//常规日期字体色
    private int mSelectDayColor = Color.parseColor("#FFFFFF");//当日日期字体色
    private int mSelectBGColor = Color.parseColor("#EA5A67");//选中日期背景色
    private int mCurrentBGColor = Color.parseColor("#EEEEEE");//当前日期背景色
    private int mCurrYear,mCurrMonth,mCurrDay;//当前日期
    private int mSelYear,mSelMonth,mSelDay;//选中日期
    private int[] weekDays;//一周存储
    private DateClick dateClick;//日期点击事件
    private DisplayMetrics mDisplayMetrics;
    private int mColumnSize,mRowSize;
    private int mDaySize = 18;//日期字体大小
    private int offset;//偏移量 10
    private String[] tagDays = new String[]{"2016-08-31"};//需标记的日期
    private int tagRadius;//小圆半径 3

    private int paddingX,paddingY;
    private int downX,downY;

    public WeekDayView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mDisplayMetrics = getResources().getDisplayMetrics();
        Calendar calendar = Calendar.getInstance();
        mDayPaint = new Paint();
        mDayBGPaint = new Paint();
        mDayTagPaint = new Paint();
        mCurrYear = calendar.get(Calendar.YEAR);
        mCurrMonth = calendar.get(Calendar.MONTH);
        mCurrDay = calendar.get(Calendar.DATE);
        setSelectYearMonth(mCurrYear,mCurrMonth,mCurrDay);
        init();
    }

    private void init(){
        paddingX = paddingY = (int) (5*mDisplayMetrics.density);
        offset = (int) (10*mDisplayMetrics.density);
        tagRadius = (int) (3*mDisplayMetrics.density);
        weekDays = DateUtils.getWeekDays(mSelYear,mSelMonth,mSelDay);
        mDayPaint.setTextSize(mDaySize*mDisplayMetrics.scaledDensity);//sp换算dp
        mDayPaint.setAntiAlias(true);
        mDayBGPaint.setStrokeWidth(3.0f*mDisplayMetrics.density);
        mDayBGPaint.setAntiAlias(true);
        mDayTagPaint.setAntiAlias(true);
    }
    /**
     * 设置年月
     * @param year
     * @param month
     * @param day
     */
    public void setSelectYearMonth(int year,int month,int day){
        this.mSelYear = year;
        this.mSelMonth = month;
        this.mSelDay = day;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(measuredWidth(widthMeasureSpec),measuredHeight(heightMeasureSpec));
    }

    private int measuredWidth(int measureSpec){
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);
        if(specMode == MeasureSpec.EXACTLY){
            result = specSize;
        }else{
            result = getHeight();
            if(specMode == MeasureSpec.AT_MOST){
                result = Math.min(result,specSize);
            }
            Log.d("DateView",result+"");
        }
        return result;
    }

    private int measuredHeight(int measureSpec){
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);
        if(specMode == MeasureSpec.EXACTLY){
            result = specSize;
        }else{
            result = (int) (ROW_HEIGHT * mDisplayMetrics.scaledDensity);
            if(specMode == MeasureSpec.AT_MOST){
                result = Math.min(result,specSize);
            }
            Log.d("DateView",result+"");
        }
        return result;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawColor(mSelectDayColor);
        mColumnSize = getWidth() / NUM_COLUMNS;
        mRowSize = getHeight();
        String dayString;
        for (int i=0;i<weekDays.length;i++){
            if(weekDays[i] == 0){
                continue;
            }
            dayString = String.valueOf(weekDays[i]);
            int startX = (int)(mColumnSize * i + (mColumnSize - mDayPaint.measureText(dayString))/2);
            int startY = (int)(mRowSize/2 - (mDayPaint.ascent() + mDayPaint.descent())/2);
            int cx = mColumnSize*i + mColumnSize/2;
            int cy = mRowSize/2;
            if(dayString.equals(String.valueOf(mSelDay))){//绘制日期是选择日期
                if(mSelDay == mCurrDay && mSelMonth == mCurrMonth && mSelYear == mCurrYear) {//如果选择日期是当日
                    mDayBGPaint.setColor(mSelectBGColor);
                    mDayBGPaint.setStyle(Paint.Style.FILL);
                    //设置字体颜色
                    mDayPaint.setColor(mSelectDayColor);
                    mDayTagPaint.setColor(mSelectDayColor);
                }else{
                    mDayBGPaint.setColor(mSelectBGColor);
                    mDayBGPaint.setStyle(Paint.Style.STROKE);
                    //设置字体颜色
                    mDayPaint.setColor(mDayColor);
                    mDayTagPaint.setColor(mSelectBGColor);
                }
                drawDayBGRect(i,canvas);
            } else {//绘制日期是非选择日期
                if(dayString.equals(String.valueOf(mCurrDay)) && mSelDay != mCurrDay &&
                        mSelMonth == mCurrMonth && mSelYear == mCurrYear) {//如果非选择日期是当日
                    mDayBGPaint.setColor(mCurrentBGColor);
                    mDayBGPaint.setStyle(Paint.Style.STROKE);
                    drawDayBGRect(i, canvas);
                    mDayPaint.setColor(mDayColor);
                    mDayTagPaint.setColor(mSelectBGColor);
                }else {
                    //设置字体颜色
                    mDayPaint.setColor(mDayColor);
                    mDayTagPaint.setColor(mSelectBGColor);
                }
            }
            canvas.drawText(dayString,startX,startY-offset,mDayPaint);
            drawTagCircle(cx,cy,canvas,dayString);
        }
    }

    private void drawTagCircle(int cx,int cy,Canvas canvas,String dayString){
        for (String tagDay:tagDays) {
            if (DateUtils.isEqualDay(mSelYear,mSelMonth,Integer.valueOf(dayString),tagDay)) {
                canvas.drawCircle(cx, cy + offset, tagRadius, mDayTagPaint);
            }
        }
    }

    /**
     * 绘制矩形背景
     * @param column
     * @param canvas
     */
    private void drawDayBGRect(int column,Canvas canvas){
        //绘制当前日期矩形
        int startRectX = mColumnSize * column;
        int startRectY = 0;
        int endRectX = startRectX + mColumnSize;
        int endRectY = startRectY + mRowSize;
        int cx = startRectX + (endRectX - startRectX)/2;
        int cy = startRectY + (endRectY - startRectY)/2;
        int radius =  (endRectY - startRectY)/2 - paddingY;//为了更好的显示圆
        canvas.drawCircle(cx,cy,radius,mDayBGPaint);
//        RectF rectF = new RectF(startRectX + paddingX, startRectY + paddingY, endRectX - paddingX, endRectY - paddingY);
//        canvas.drawRoundRect(rectF, 10, 10, mDayBGPaint);//绘制圆角矩形
    }

    private int currX,currY;
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        int X = (int)event.getX();
        int Y = (int)event.getY();
        switch (action){
            case MotionEvent.ACTION_DOWN:
                downX = currX = X;
                downY = currY = Y;
                break;
            case MotionEvent.ACTION_MOVE:
//                setTranslationY(X - currX);
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                if(Math.abs(X - downX)<10&&Math.abs(Y - downY)<10){
                    performClick();
                    doClickAction((X + downX)/2,(Y + downY)/2);
                }
                break;
        }
        return true;
    }

    /**
     * 设置年月日
     * @param year
     * @param month
     * @param day
     */
    public void setDay(int year,int month,int day){
        setSelectYearMonth(year,month,day);
        init();
        invalidate();
    }

    /**
     * API
     * 上一个月，日历向后翻页
     */
    public void onLastMonth(){
        int year = mSelYear;
        int month = mSelMonth;
        int day = 1;
        if(month == 0){//若果是1月份，则变成12月份
            year = mSelYear-1;
            month = 11;
        }else if(DateUtils.getMonthDays(year, month) == day){
            //如果当前日期为该月最后一点，当向前推的时候，就需要改变选中的日期
            month = month-1;
            day = DateUtils.getMonthDays(year, month);
        }else{
            month = month-1;
        }
        setSelectYearMonth(year,month,day);
        init();
        setTagDays(new String[]{});
        requestLayout();
        invalidate();
    }

    /**
     * API
     * 下一个月，日历向前翻页
     */
    public void onNextMonth(){
        int year = mSelYear;
        int month = mSelMonth;
        int day = 1;
        if(month == 11){//若果是12月份，则变成1月份
            year = mSelYear+1;
            month = 0;
        }else if(DateUtils.getMonthDays(year, month) == day){
            //如果当前日期为该月最后一点，当向前推的时候，就需要改变选中的日期
            month = month + 1;
            day = DateUtils.getMonthDays(year, month);
        }else{
            month = month + 1;
        }
        setSelectYearMonth(year,month,day);
        init();
        setTagDays(new String[]{});
        requestLayout();
        invalidate();
    }

    /**
     * API
     * 跳转至某天
     */
    public void setToDateToView(int year,int month,int day){
        mSelYear = year;
        mSelMonth = month;
        mSelDay = day;
        if(month == 11){//若果是12月份，则变成1月份
            year = mSelYear+1;
            month = 0;
        }else if(DateUtils.getMonthDays(year, month) == day){
            //如果当前日期为该月最后一点，当向前推的时候，就需要改变选中的日期
            month = month + 1;
            day = DateUtils.getMonthDays(year, month);
        }else{
            month = month + 1;
        }
        setSelectYearMonth(mSelYear,mSelMonth,mSelDay);
        init();
        requestLayout();
        invalidate();
    }

    /**
     * API
     * 跳转至今天
     */
    public void setTodayToView(){
        setSelectYearMonth(mCurrYear,mCurrMonth,mCurrDay);
        init();
        invalidate();
    }

    public void setTagDays(String[] tagDays){
        this.tagDays = tagDays;
        invalidate();
    }

    /**
     * 执行点击事件
     * @param x
     * @param y
     */
    private void doClickAction(int x,int y){
        int row = y / mRowSize;
        int column = x / mColumnSize;
        if(weekDays[column] != 0) {
            setSelectYearMonth(mSelYear, mSelMonth, weekDays[column]);
            invalidate();
            //执行activity发送过来的点击处理事件
            if (dateClick != null) {
                dateClick.onDateClick(mSelYear, mSelMonth, weekDays[column]);
            }
        }
    }

    /**
     * 点击日期回调事件
     */
    public interface DateClick{
        void onDateClick(int year,int month,int day);
    }

    /**
     * API
     * 设置日期点击事件
     * @param dateClick
     */
    public void setOnDateClick(DateClick dateClick){
        this.dateClick = dateClick;
    }
}
